<script setup lang="ts">
import {markRaw, toRaw,ref,onMounted,watch,nextTick} from "vue";
import ReCol from "@/components/ReCol";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import WelcomeTable from "./components/table/index.vue";
import GenJinChart from "./components/genjin.vue";
import {BarChart,DateSelect,DateSelect1} from "./components/charts";
import {welcomeIndex,welcomeIndex1,welcomeOrder,welcomePurchase,welcomeCaiji,welcomeCaiwu,welcomeQushi,welcomeCustomerAssignment,welcomePendingCustomers,welcomeTaskStatistics} from "@/api/statistics";
import {getSalesList} from "@/api/crm";
defineOptions({
  name: "Welcome"
});
onMounted(() => {
  getData();
});
const sdata = ref<any>({ purchase: [], dongtai: [] })
const sdata1 = ref<any>({})
const customerAssignmentData = ref([])
const salesmanList = ref([])
const selectedSalesman = ref(null)
const pendingCustomersData = ref({ total: 0, details: [] })
const taskStatisticsData = ref([])
const selectedTaskFollower = ref(null)

async function getData(){
  var { data } = await welcomeIndex(toRaw({}))
  sdata.value = data
  var { data } = await welcomeIndex1(toRaw({}))
  sdata1.value = data
  
  // 获取销售人员列表（会自动获取当前用户的客户分配数据）
  await getSalesmanList()
  
  // 获取待轮询客户数据
  await getPendingCustomersData()
  
  // 获取任务统计数据
  await getTaskStatisticsData()
}

// 获取销售人员列表
async function getSalesmanList(){
  try {
    const response: any = await getSalesList({page: 1, limit: 1000})
    salesmanList.value = response.data.data || []
    
    // 默认选中当前用户
    if(response.data.me && !selectedSalesman.value) {
      const currentUserId = Number(response.data.me.id)
      
      // 检查当前用户是否在销售人员列表中
      const userInList = salesmanList.value.find(user => Number(user.id) === currentUserId)
      
      if(userInList) {
        selectedSalesman.value = currentUserId
        selectedTaskFollower.value = currentUserId // 同时设置任务跟进人员
        console.log('默认选中用户:', selectedSalesman.value, response.data.me.username)
        
        // 等待DOM更新后获取客户分配数据
        await nextTick()
        await getCustomerAssignmentData()
      } else {
        console.log('当前用户不在销售人员列表中，跳过默认选择')
        // 如果当前用户不在列表中，但列表不为空，选择第一个
        if(salesmanList.value.length > 0) {
          selectedSalesman.value = Number(salesmanList.value[0].id)
          selectedTaskFollower.value = Number(salesmanList.value[0].id) // 同时设置任务跟进人员
          console.log('选择列表中第一个用户:', selectedSalesman.value, salesmanList.value[0].username)
          await nextTick()
          await getCustomerAssignmentData()
        }
      }
    }
    
    console.log('销售人员列表:', salesmanList.value)
    console.log('当前用户信息:', response.data.me)
  } catch (error) {
    console.error('获取销售人员列表失败:', error)
  }
}

// 获取客户分配统计数据
async function getCustomerAssignmentData(){
  try {
    const params = selectedSalesman.value ? {effective_id: selectedSalesman.value} : {}
    const response: any = await welcomeCustomerAssignment(params)
    customerAssignmentData.value = response.data || []
  } catch (error) {
    console.error('获取客户分配统计失败:', error)
    customerAssignmentData.value = []
  }
}

// 销售人员切换时重新获取数据
async function onSalesmanChange(){
  console.log('销售人员切换:', selectedSalesman.value)
  await getCustomerAssignmentData()
}

// 获取待轮询客户数据
async function getPendingCustomersData(){
  try {
    const response: any = await welcomePendingCustomers()
    pendingCustomersData.value = response.data || { total: 0, details: [] }
  } catch (error) {
    console.error('获取待轮询客户统计失败:', error)
    pendingCustomersData.value = { total: 0, details: [] }
  }
}

// 获取任务统计数据
async function getTaskStatisticsData(){
  try {
    const params = selectedTaskFollower.value ? {follower_id: selectedTaskFollower.value} : {}
    const response: any = await welcomeTaskStatistics(params)
    taskStatisticsData.value = response.data || []
  } catch (error) {
    console.error('获取任务统计失败:', error)
    taskStatisticsData.value = []
  }
}

// 任务跟进人员切换时重新获取数据
async function onTaskFollowerChange(){
  console.log('任务跟进人员切换:', selectedTaskFollower.value)
  await getTaskStatisticsData()
}

// 监控selectedSalesman的变化
watch(selectedSalesman, (newVal, oldVal) => {
  console.log('selectedSalesman变化:', { oldVal, newVal })
}, { immediate: true })
import { useRouter } from 'vue-router'
import {OptionsType} from "@/components/ReSegmented";

const router = useRouter()

const openNewTab = (item) => {
  let path;
  
  // 如果是字符串（直接传递路径），直接使用
  if (typeof item === 'string') {
    path = item;
  } 
  // 如果是对象，检查是否有link属性
  else if (item && typeof item === 'object') {
    // 优先使用link属性（客户分配统计）
    if (item.link) {
      path = item.link;
    }
    // 如果没有link但是对象本身可能是路径（相关统计的旧格式）
    else if (typeof item.value === 'string' && item.value.includes('/')) {
      path = item.value;
    }
    // 其他情况，尝试将整个对象转为字符串
    else {
      console.warn('未能识别的item格式，尝试toString:', item);
      path = item.toString();
    }
  } else {
    console.error('无效的跳转参数:', item);
    return;
  }

  console.log('跳转路径:', path);
  
  // 解析路径和查询参数
  const [basePath, queryString] = path.split('?');
  let query = {};
  
  if (queryString) {
    query = queryString.split('&').reduce((acc, pair) => {
      const [key, value] = pair.split('=');
      acc[key] = decodeURIComponent(value || '');
      return acc;
    }, {});
  }

  console.log('解析的查询参数:', query);
  
  router.push({
    path: basePath,
    query: query
  });
}
const log_column = [
  {label: "操作类型", prop: "log_type",width:100,showOverflowTooltip:true},
  {label: "订单Id", prop: "order_id",width:130,showOverflowTooltip:true},
  {label: "备注",width: 100, showOverflowTooltip:true, prop: "remark"},
  {label: "操作员",width:60,prop: "creator",showOverflowTooltip:true},
  {label: "操作时间", width: 120, prop: "created_at"},
  {label: "描述",showOverflowTooltip:true,prop: "content"},
];
</script>

<template>
  <div>
    <el-row :gutter="15" justify="space-around">
      <re-col v-motion class="mb-[18px]" :value="14" :md="12" :sm="12" :xs="24" :initial="{ opacity: 0, y: 100 }"
              :enter="{opacity: 1,y: 0, transition: { delay: 80 * 5 } }">

        <el-card class="bar-card" shadow="never"  v-perms="'button:welcome:order_report'">
          <DateSelect title="简报" :api="welcomeOrder" :size="4"/>
        </el-card>
        <el-card class="bar-card mt-[15px]" shadow="never" v-perms="'button:welcome:order_step_status'">
          <DateSelect1 title="跟进状态" :api="welcomePurchase"  :size="4"/>
        </el-card>

        <el-card class="bar-card mt-[15px]" shadow="never" v-perms="'button:welcome:order_anys'">
          <GenJinChart id="barChart2" height="340" width="100%" :api="welcomeQushi" class="mt-[15px] bg-[var(--el-bg-color-overlay)]"/>
        </el-card>

      </re-col>
      <!-- 右边-->
      <re-col
        v-motion class="mb-[18px]" :value="10" :md="12" :sm="12" :xs="24" :initial="{ opacity: 0, y: 100 }"
        :enter="{opacity: 1,y: 0, transition: { delay: 560 }}">

        <el-card class="bar-card " shadow="never" > <!--"'button:welcome:task_statistics'" -->
          <div class="flex justify-between items-center">
            <span class="text-md font-medium">我的任务</span>
            <el-select 
              v-model="selectedTaskFollower" 
              placeholder="请选择跟进人员" 
              filterable
              @change="onTaskFollowerChange"
              style="width: 200px;"
              clearable>
              <el-option
                v-for="item in salesmanList"
                :key="item.id"
                :label="item.username"
                :value="item.id">
                <span style="float: left">{{ item.username }}</span>
                <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                  {{ item.dept?.name || '' }}
                </span>
              </el-option>
            </el-select>
          </div>
          <div class="flex justify-between items-start mt-2 kfcg">
            <re-col v-motion v-for="(item, index) in taskStatisticsData" :key="index"
                    :value="6" :md="12" :sm="12" :xs="24" :initial="{ opacity: 0, y: 100 }"
                    :enter="{opacity: 1,y: 0, transition: { delay: 80 * (index + 1) } }">
              <div class=" justify-between items-start mt-2">
                <p class="font-medium2 text-sm" @click="openNewTab(item)">{{item.value}}</p><p class="font-txt text-xs">{{item.name}}</p>
              </div>
            </re-col>
          </div>
        </el-card>

        <el-card class="bar-card mt-[15px]" shadow="never" v-perms="'button:welcome:order_statistics'">
          <div class="flex justify-between items-center">
            <span class="text-md font-medium">我的客户</span>
            <el-select 
              v-model="selectedSalesman" 
              placeholder="请选择跟进人员" 
              filterable
              @change="onSalesmanChange"
              style="width: 200px;"
              clearable>
              <el-option
                v-for="item in salesmanList"
                :key="item.id"
                :label="item.username"
                :value="item.id">
                <span style="float: left">{{ item.username }}</span>
                <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                  {{ item.dept?.name || '' }}
                </span>
              </el-option>
            </el-select>
          </div>
          <div class="flex justify-between items-start mt-2 kfcg">
            <re-col v-motion v-for="(item, index) in customerAssignmentData" :key="index"
                    :value="4" :md="8" :sm="12" :xs="24" :initial="{ opacity: 0, y: 100 }"
                    :enter="{opacity: 1,y: 0, transition: { delay: 80 * (index + 1) } }">
              <div class=" justify-between items-start mt-2">
                <p class="font-medium2 text-sm" @click="openNewTab(item)">{{item.value}}</p><p class="font-txt text-xs">{{item.name}}</p>
              </div>
            </re-col>
          </div>
        </el-card>

        <el-card class="bar-card mt-[15px]" shadow="never" v-perms="'button:welcome:customer_pending'">
          <div class="flex justify-between items-center">
            <span class="text-md font-medium">待分配客户</span>
          
          </div>
          <div class="flex justify-between items-start mt-2 kfcg">
            <re-col v-motion v-for="(item, index) in pendingCustomersData.details" :key="index"
                    :value="8" :md="12" :sm="12" :xs="24" :initial="{ opacity: 0, y: 100 }"
                    :enter="{opacity: 1,y: 0, transition: { delay: 80 * (index + 1) } }">
              <div class=" justify-between items-start mt-2">
                <p class="font-medium2 text-sm" @click="openNewTab(item)">{{item.value}}</p><p class="font-txt text-xs">{{item.name}}</p>
              </div>
            </re-col>
          </div>
        </el-card>


        <el-card class="bar-card mt-[15px]" shadow="never" v-perms="'button:welcome:order_statistics'">
          <div class="flex justify-between">
            <span class="text-md font-medium">相关统计</span>
          </div>
          <div class="flex justify-between items-start mt-3 kfcg">
            <re-col v-motion v-for="(item, index) in sdata.purchase" :key="index"
                    :value="6" :md="12" :sm="12" :xs="24" :initial="{ opacity: 0, y: 100 }"
                    :enter="{opacity: 1,y: 0, transition: { delay: 80 * (index + 1) } }">
              <div class=" justify-between items-start mt-3">
                <p class="font-medium2" @click="openNewTab(item)">{{item.value}}</p><p class="font-txt">{{item.name}}</p>
              </div>
            </re-col>
          </div>
        </el-card>


        <el-card class="bar-card mt-[15px]" shadow="never" v-perms="'button:welcome:order_dynamics'">
          <div class="flex justify-between">
            <span class="text-md font-medium">订单动态</span>
          </div>
          <div class="flex h-[420px] mt-[15px]">
            <pure-table  max-height="420" size="small" :data="sdata.dongtai" :columns="log_column"/>
          </div>
        </el-card>


      </re-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card) {
  --el-card-border-color: none;

  /* 解决概率进度条宽度 */
  .el-progress--line {
    width: 85%;
  }

  /* 解决概率进度条字体大小 */
  .el-progress-bar__innerText {
    font-size: 15px;
  }

  /* 隐藏 el-scrollbar 滚动条 */
  .el-scrollbar__bar {
    display: none;
  }

  /* el-timeline 每一项上下、左右边距 */
  .el-timeline-item {
    margin: 0 6px;
  }
}

.main-content {
  margin: 20px 20px 0 !important;
}
.icon22{
  width:40px;height: 40px;border-radius: 50%;
}
.font-medium{font-size: 15px;}
.kfcg .font-medium2{color:#0d84ff}
.green .font-medium2{color: #197a46
}
.yellow .font-medium2{color: #f3b45a
}
.font-medium2{font-size: 18px;cursor: pointer}
.icon33{
  display: flex;align-items: center;width: 24px; height: 24px; margin-top: 8px;margin-left: 8px;
}
.font-txt{
  font-size: 12px;
}
</style>
